let _Vue = null
class VueRouterHash {
  static install (Vue) {
    if (VueRouterHash.install.installed) return

    VueRouterHash.install.installed = true

    _Vue = Vue

    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      },
    })

  }

  constructor(options) {
    this.options = options
    this.routerMap = {}
    this.data = _Vue.observable({ current: '/' })  // 响应式数据是核心，current变化时，触发视图更新
  }

  init () {
    this.createRouteMap()
    this.initEvent()
    this.initComponents()
  }

  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routerMap[route.path] = route.component
    })
  }

  initComponents () {
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [])
      },
      methods: {
        clickHandler (e) {
          // 更改hash，触发hashchange
          window.location.hash = this.to
          e.preventDefault()
        }
      },
    })

    Vue.component('router-view', {
      render (h) {
        const compoent = this.routerMap[this.data.current]
        h(compoent, {}, [])
      }
    })
  }

  initEvent () {
    window.addEventListener('hashchange', () => {
      // hashchange事件触发后，获取最新hash，赋值给current，进而触发渲染，更新视图
      const hash = window.location.hash.slice(1)
      this.data.current = hash
    })
  }
}